package com.xci.sys.controller;

import cn.hutool.core.map.MapUtil;
import com.xci.core.annotation.AllowAnonymous;
import com.xci.core.annotation.Authorize;
import com.xci.core.base.GMap;
import com.xci.core.base.RestMessage;
import com.xci.core.base.WebController;
import com.xci.core.domain.LoginModel;
import com.xci.core.helper.CookieHelper;
import com.xci.core.helper.Helper;
import com.xci.core.helper.WebHelper;
import com.xci.core.internal.Const;
import com.xci.core.internal.Sys;
import com.xci.core.web.EasyUITreeHelper;
import com.xci.core.web.TreeNode;
import com.xci.sys.entity.SysModule;
import com.xci.sys.entity.SysUser;
import com.xci.sys.service.LockUserService;
import com.xci.sys.service.ModuleService;
import com.xci.sys.service.OnlineUserService;
import com.xci.sys.service.UserService;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限子系统默认控制器
 */
@Authorize
@Controller("sysDefaultController")
@RequestMapping("/sys")
public class DefaultController extends WebController {
    @Resource
    private UserService userService;//用户服务
    @Resource
    private ModuleService moduleService;//模块服务
    @Resource
    private OnlineUserService onlineUserService;//在线用户服务
    @Resource
    private LockUserService lockUserService;//锁定用户服务
    @Resource
    private Cache captchaCache;//用户验证码缓存

    //region 页面视图

    // @GetMapping("/")
    @GetMapping()
    public String index(ModelMap map) {
        map.put("currentUser", getCurrentUser());
        map.put("systemTitle", Sys.me().getParamValue("SystemTitle", "西交投信息系统开发平台"));
        map.put("systemTitleColor", Sys.me().getParamValue("SystemTitleColor", "white"));
        map.put("systemCopyright", Sys.me().getParamValue("SystemCopyright", "西安交通信息投资营运有限公司 版权所有"));
        map.put("systemTitleVersion", Sys.me().getParamValue("SystemTitleVersion", "测试版"));
        map.put("systemTitleVersionColor", Sys.me().getParamValue("SystemTitleVersionColor", "yellow"));

        map.put("systemEnableOnlineUserRefresh", Sys.me().getParamValue("SystemEnableOnlineUserRefresh", "0"));
        map.put("systemEnableMessageRefresh", Sys.me().getParamValue("SystemEnableMessageRefresh", "0"));
        map.put("systemEnableTabPage", Sys.me().getParamValue("SystemEnableTabPage", "0"));

        return "sys/default/index";
    }

    @GetMapping("/home")
    public String home(ModelMap map) {
        map.put("userOwneRoleString", Sys.me().getRoleName(getCurrentUser()));
        return "sys/default/home";
    }

    @AllowAnonymous
    @GetMapping("/login")
    public String login(HttpServletRequest request, ModelMap map) {
        if(!WebHelper.checkBrowserCompatibility()) {
            return redirect("/compatibility");
        }
        boolean loginResult = Sys.me().checkAndAutoLogin(request);
        if(loginResult) {
            return redirect(Sys.setting().getWeb().getDefaultUrl());
        }
        map.put("systemTitle", Sys.me().getParamValue("SystemTitle", "西交投信息系统开发平台"));
        map.put("systemTitleColor", Sys.me().getParamValue("SystemTitleColor", "white"));
        map.put("systemCopyright", Sys.me().getParamValue("SystemCopyright", "西安交通信息投资营运有限公司 版权所有"));
        return "sys/default/login";
    }

    @AllowAnonymous
    @GetMapping("/unauthorized")
    public String unauthorized() {
        return "error/unauthorized";
    }

    @AllowAnonymous
    @GetMapping("/about")
    public String about(ModelMap map) {
       // List<ReleaseHistoryEntity> list = releaseHistoryService.query(GMap.newMap("hasContent", "1"));
       // map.put("releaseHistoryList", list);
        return "sys/default/about";
    }

    /**
     * 模块Tree
     */
    @ResponseBody
    @GetMapping("/tree")
    public Object tree(@RequestParam Map<String, Object> params) {
        List<SysModule> list = moduleService.getUserModuleCacheList(getCurrentUser()).stream().filter(
                p -> p.getIsMenu() && p.getIsWeb()).collect(Collectors.toList());
        List<TreeNode> models = moduleService.convertToNodeList(list);
        return EasyUITreeHelper.restTree(models);
    }

    //endregion

    //region 公共视图

    /**
     * 图标页面
     */
    @AllowAnonymous
    @GetMapping("/icon")
    public String icon() {
        return "sys/default/icon";
    }

    /**
     * 浏览器兼容性页面
     */
    @AllowAnonymous
    @GetMapping("/compatibility")
    public String compatibility() {
        return "sys/default/compatibility";
    }

    //endregion

    //region 数据处理

    @AllowAnonymous
    @ResponseBody
    @PostMapping("/login")
    public RestMessage login(@ModelAttribute LoginModel model, HttpServletRequest request) {
        String account = model.getAccount();
        if(Helper.isBlank(model.getUuid())) {
            return RestMessage.fail("账号密码错误");
        }
        if(lockUserService.isLock(account)) {
            return RestMessage.fail("账号错误次数达到上限,暂时被锁定");
        }
        model.setCaptcha(captchaCache.get(account, String.class));
        RestMessage<SysUser> result = userService.login(account, model.getPassword(), model.getCaptcha());
        if(result.isFail()) {
            return result;
        }

        var entity = result.getData();
        RestMessage sresult = Sys.me().onLoginSuccess(entity);
        if(!sresult.isSuccess()) {
            return sresult;
        }
        if(model.isAutoLogin()) {
            Sys.me().setUserJwtCookie(entity);
        }
        return RestMessage.success(GMap.newMap("url", Sys.setting().getWeb().getDefaultUrl()));
    }

    /**
     * 检查账号锁定状态
     */
    @AllowAnonymous
    @ResponseBody
    @PostMapping("/checkLock")
    public RestMessage checkLock(String account) {
        if(lockUserService.requireCaptcha(account)) {
            return RestMessage.success();
        }
        return RestMessage.fail();
    }

    @ResponseBody
    @PostMapping("/logout")
    public RestMessage logout() {
        userService.logout(getCurrentUser().getId());
        getSession().removeAttribute(Const.CURRENT_USER_Session_KEY);
        CookieHelper.removeCookie(Const.CURRENT_USER_COOKIE_KEY);
        return RestMessage.success(MapUtil.of("url", Sys.setting().getWeb().getLoginUrl()));
    }

    //endregion
}